package com.liusy.common;

import java.beans.*;
import java.io.*;



public class ObjectXMLSerializer {
	/**
	 * 对象转换为XML字符串
	 * 
	 * @param obj 要转换的对象
	 * @result String 返回XML字符串
	 */
	public static String serialize(Object obj) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		BufferedOutputStream oos = new BufferedOutputStream(baos);
		XMLEncoder xmlEncoder = new XMLEncoder(oos);
		xmlEncoder.writeObject(obj);
		xmlEncoder.close();
		return baos.toString();
	}

	/**
	 * XML字符串转换为对象
	 * 
	 * @param xmlString 要转换的XML字符串
	 * @result T 返回对象
	 */
	@SuppressWarnings("unchecked")
	public static <T> T deserialize(Class<T> type, String xmlString) {
		ByteArrayInputStream bais = new ByteArrayInputStream(xmlString.getBytes());
		BufferedInputStream ois = new BufferedInputStream(bais);
		XMLDecoder xmlDecoder = new XMLDecoder(ois);
		Object readObject = xmlDecoder.readObject();
		return (T) readObject;
	}
}